<?php
/**
 *	KLF Framework
 *
 *	@author Kristian Oye <kristianoye@gmail.com> 
 *	@copyright (C) 2010-2011, Kristian Oye
 */
namespace KLF\System\Web\Routing
{
	use KLF\System\KEvent;
	use KLF\System\KComponent;
	use KLF\System\IDisposable;
	use KLF\System\Web\KHttpApplication;
	use KLF\System\Web\IHttpModule;
	use KLF\System\Web\KHttpContext;
	use KLF\System\Web\Events\KPostResolveRequestCache;
	
	/**
	 *  Class KUrlRoutingModule
	 *
	 *  @package KLF\System\Web\Routing
	 *  @access public
	 *  @author Kristian Oye <kristianoye@gmail.com>
	 *  @since 0.1
	 *  
	 *  @method KUrlRoutingModule NewInstance
	 *  
	 *  @property KHttpContext $Context The request context
	 *  @property KRouteCollection $RouteCollection The route collection
	 *  @property KPostResolveRequestCache $eventPostResolveRequestCache Routing event
	 *  @method KPostResolveRequestCache eventPostResolveRequestCache() Fires the PostResolveRequestCache event.
	 */
	class KUrlRoutingModule extends KComponent implements IHttpModule
	{
		/**
		 * The context representing the request and response.
		 * 
		 * @var KHttpContext $_propContext 
		 */
		protected $_propContext;
		
		/**
		 * The collection of routes to evaluate.
		 * 
		 * @var KRouteCollection $_propRouteCollection
		 */
		protected $_propRouteCollection;
		
		/**
		 * @var \KLF\System\Web\Routing\Events\KPostResolveRequestCache $_eventPostResolveRequestCache
		 */
		protected $_eventPostResolveRequestCache;
		
		/**
		 * Construct a new KUrlRoutingModule
		 *
		 * @author Kristian Oye <kristianoye@gmail.com>
		 * @since 0.1
		*/
		public function __construct(KRouteCollection $collection)
		{
			$this->_propRouteCollection = $collection;
			$this->_eventPostResolveRequestCache = new KPostResolveRequestCache($this);
		}
		
		/**
		 * Initialize the object with a new request reference
		 *
		 * @author Kristian Oye <kristianoye@gmail.com>
		 * @since 0.1
		 * @param KHttpContext $context
		 * @return KUrlRoutingModule Reference to this object
		*/
		public function Initialize(KHttpApplication $app)
		{
			$this->_propContext = $app->Context;
		}
		
		/**
		 * Attempts to map the request to a controller, etc.
		 *
		 * @author Kristian Oye <kristianoye@gmail.com>
		 * @since 0.1
		 * 
		 * @return \KLF\System\Web\Routing\KRouteContext
		*/
		public function ResolveRequest()
		{
			foreach($this->_propRouteCollection as $route)
			{
				/* @var $route KRoute */
				if (($data = $route->GetRouteData($this->Context)))
				{
					return new KRouteContext($this->Context, $data, $this->_propRouteCollection);
				}
			}
			return false;
		}
	}
}
